<template>

  <page-header-wrapper>

    <template #extra>
      <a-button type="primary" v-if="!updateActionDate.state" @click="backToList" :disabled="loading">
        返回商品列表
      </a-button>
      <a-button type="primary" v-if="!updateActionDate.state" @click="toAddToMainPageRecommendGoods"
                :disabled="loading">
        添加到首页
      </a-button>
      <a-button type="primary" v-if="!updateActionDate.state" @click="toStartEditGood" :disabled="loading">
        修改
      </a-button>
      <a-button :loading="uploadingMainImage||uploadingSubImageImage" type="primary" style="margin-left: 10px"
                @click="toSubmitEditGood" v-if="updateActionDate.state" :disabled="loading">
        保存
      </a-button>
      <a-button type="primary" style="margin-left: 10px"
                v-if="updateActionDate.state" :disabled="loading"
                @click="toCancelEditGood">
        返回
      </a-button>
      <a-button style="margin-left: 10px" type="danger" v-if="!updateActionDate.state" :disabled="loading"
                @click="toDeleteGood">
        删除该商品
      </a-button>
    </template>

    <div class="table-page-search-wrapper">
      <a-spin size="large" :spinning="loading&&updateActionDate.data==null">
        <a-card :title="'商品详情 ID:'+ goodId" :loading="loading">
          <div v-if="!(updateActionDate.data==null)">
            <a-form :layout="'inline'">
              <a-row :gutter="48">
                <a-col :lg="8" :md="12" :xs="24">
                  <a-form-item label=" 商品名称">
                    <a-input :read-only="!updateActionDate.state" v-model:value="updateActionDate.data.name"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :lg="8" :md="12" :xs="24">
                  <a-form-item label="供货商">
                    <a-input :read-only="!updateActionDate.state"
                             v-model:value="updateActionDate.data.producer"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :lg="8" :md="12" :xs="24">
                  <a-form-item label="销售状态">
                    <a-badge :color="updateActionDate.data.status==1?'green':'red'"
                             :text="updateActionDate.data.status==1?'售卖中':'停售中'"/>
                    <a-button style="margin-left: 10px" type="link" :disabled="updateActionDate.state"
                              @click="toChangeStatus">切换
                    </a-button>
                  </a-form-item>
                </a-col>

                <a-col :lg="8" :md="12" :xs="24">
                  <a-form-item label="市场价">

                    <a-input v-if="updateActionDate.state"
                             v-model:value="updateActionDate.data.fakePrice"></a-input>
                    <span v-else>
                      {{ updateActionDate.data.fakePrice == null ? '未设定' : updateActionDate.data.fakePrice }}
                    </span>
                  </a-form-item>
                </a-col>
                <a-col :lg="8" :md="12" :xs="24">
                  <a-form-item label="库存数量">
                    {{ updateActionDate.data.stock == null ? 0 : updateActionDate.data.stock }}
                  </a-form-item>
                </a-col>
                <a-col :lg="8" :md="12" :xs="24">
                  <a-form-item :read-only="true" label="分类">
                    <div v-if="!updateActionDate.state">
                        <span v-if="updateActionDate.data.primaryTypeId!=null">
            {{
                            typeMap.get(updateActionDate.data.primaryTypeId).type == null ? '未知分类' : typeMap.get(updateActionDate.data.primaryTypeId).type
                          }}
              <span v-if="updateActionDate.data.secondaryTypeId!=null">
                {{
                  typeMap.get(updateActionDate.data.secondaryTypeId) != null ? (' / ' + typeMap.get(updateActionDate.data.secondaryTypeId).type) : null
                }}
                <span v-if="updateActionDate.data.tertiaryTypeId!=null">
            {{
                    typeMap.get(updateActionDate.data.tertiaryTypeId) != null ? (' / ' + typeMap.get(updateActionDate.data.tertiaryTypeId).type) : null
                  }}
                </span>
              </span>
            </span>
                      <span v-else>
              未知分类
            </span>
                    </div>
                    <a-cascader
                      :default-value="updateActionDate.data.primaryTypeId==null?[]:(updateActionDate.data.secondaryTypeId==null?[updateActionDate.data.primaryTypeId]:(updateActionDate.data.tertiaryTypeId==null?[updateActionDate.data.primaryTypeId,updateActionDate.data.secondaryTypeId]:[updateActionDate.data.primaryTypeId,updateActionDate.data.secondaryTypeId,updateActionDate.data.tertiaryTypeId]))"
                      v-else :field-names="{ label: 'type', value: 'id', children: 'children' }"
                      :options="JSON.parse(JSON.stringify(typeTreeList))"
                      change-on-select placeholder="Please select" @change="onGoodsTypeChange"/>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="48">
                <a-col :span="24">
                  <a-form-item label="一句话介绍">
                    <a-input :read-only="!updateActionDate.state"
                             v-model:value="updateActionDate.data.lessIntro"></a-input>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="48">
                <a-col :span="24">
                  <div data-v-53922493="" class="ant-row ant-form-item" style="height: auto;margin-bottom: 0">
                    <div class="ant-col ant-form-item-label">
                      <label title="简介图" class=""
                             style="display: flex;flex-direction: row;flex-wrap: nowrap;align-content: center;justify-content: flex-start;align-items: center;">
                        简介图
                        <a-tooltip placement="right">
                          <template slot="title">
                            格式：png、jpeg、jpg<br/>
                            尺寸：300px * 300px
                          </template>
                          <a-icon type="info-circle" style="margin: 0 5px;font-size: 16px;"/>
                        </a-tooltip>

                      </label>


                    </div>
                    <div class="ant-col ant-form-item-control-wrapper">
                      <div class="ant-form-item-control" style="height: unset">
                        <a-upload
                          list-type="picture-card"
                          :file-list="mainImage"
                          @preview="toShowPhoto"
                          :custom-request="handleUploadMainImage"
                          @change="handleMainImageChange"
                        >
                          <div v-if="mainImage.length==0&&updateActionDate.state">
                            <a-icon type="plus"/>
                            <div class="ant-upload-text">
                              Upload
                            </div>
                          </div>
                        </a-upload>
                      </div>
                    </div>
                  </div>
                </a-col>
                <a-col :span="24">
                  <div data-v-53922493="" class="ant-row ant-form-item" style="height: auto;margin-bottom: 0">

                    <div class="ant-col ant-form-item-label">
                      <label title="轮播图" class=""
                             style="display: flex;flex-direction: row;flex-wrap: nowrap;align-content: center;justify-content: flex-start;align-items: center;">
                        轮播图
                        <a-tooltip placement="right">
                          <template slot="title">
                            格式：png、jpeg、jpg<br/>
                            尺寸：600px * 600px
                          </template>
                          <a-icon type="info-circle" style="margin: 0 5px;font-size: 16px;"/>
                        </a-tooltip>

                      </label>
                    </div>
                    <div class="ant-col ant-form-item-control-wrapper">
                      <div class="ant-form-item-control" style="height: unset">
                        <a-upload
                          list-type="picture-card"
                          :file-list="subImages"
                          @preview="toShowPhoto"
                          :custom-request="handleUploadSubImage"
                          @change="handleSubImagesChange"
                        >
                          <div v-if="updateActionDate.state">
                            <a-icon type="plus"/>
                            <div class="ant-upload-text">
                              Upload
                            </div>
                          </div>
                        </a-upload>
                      </div>
                    </div>
                  </div>
                </a-col>
              </a-row>
              <a-modal v-model:visible="showPhotoData.state" :footer="null">
                <img alt="example" style="width: 100%" :src="showPhotoData.url"/>
              </a-modal>
              <a-row :gutter="48">
                <a-col :lg="8" :md="12" :xs="24">
                  <a-form-item :read-only="true" label="创建时间">
                    {{ updateActionDate.data.createAt }}
                  </a-form-item>
                </a-col>
                <a-col :lg="8" :md="12" :xs="24">
                  <a-form-item :read-only="true" label="更新时间">
                    {{ updateActionDate.data.updateAt }}
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
            <a-form>
              <a-form-item label="产品简介">
                <!--                <quill-editor-->
                <!--                  :content="updateActionDate.data.intro"-->
                <!--                  :disabled="!updateActionDate.state"-->
                <!--                  @change="onChangeIntro"-->
                <!--                />-->
                <tinymce-editor v-model:value="updateActionDate.data.intro"
                                :disable="!updateActionDate.state">
                </tinymce-editor>
              </a-form-item>
              <a-form-item label="详细介绍">
                <!--                <quill-editor-->
                <!--                  :content="updateActionDate.data.details"-->
                <!--                  :disabled="!updateActionDate.state"-->
                <!--                  @change="onChangeDetails"-->
                <!--                />-->

                <tinymce-editor v-model:value="updateActionDate.data.details"
                                :disable="!updateActionDate.state">
                </tinymce-editor>

              </a-form-item>

            </a-form>
          </div>
        </a-card>
        <div v-if="updateActionDate.data!=null" style="margin-top: 20px;">
          <a-card :loading="loading">

            <template #title>
              <div
                style="display: flex;flex-direction: row;flex-wrap: nowrap;align-content: center;justify-content: flex-start;align-items: center;">
                商品规格
                <a-tooltip placement="right">
                  <template slot="title">
                    一行为一种规格，每种规格规格可有多个选项，如：<br/>
                    大小：小、中、大<br/>
                    颜色：黄、白、绿

                  </template>
                  <a-icon type="info-circle" style="margin: 0 5px;font-size: 16px;"/>
                </a-tooltip>
              </div>
            </template>

            <a-row :gutter="[48,10]">
              <a-col :span="24" v-for="(specification,index) in updateActionDate.data.specificationList"
                     style="height: auto">
                <a-form layout="inline">
                  <div data-v-53922493="" class="ant-row ant-form-item" style="height: auto;margin-bottom: 0">
                    <div class="ant-col ant-form-item-label"><label class="">
                      <div
                        style="display: inline-flex;flex-direction: row;flex-wrap: nowrap;align-content: center;justify-content: center;align-items: center;">
                        {{ specification.attributeKey }}
                        <a-button @click="toOpenAttributeKeyModel(index)"
                                  v-if="updateActionDate.state"
                                  type="link"
                                  icon="edit"

                                  style="height:16px;width:20px;margin-left: 5px;display: inline-flex;flex-direction: column;flex-wrap: nowrap;align-content: center;justify-content: center;align-items: center;"></a-button>
                      </div>
                    </label>
                    </div>
                    <div class="ant-col ant-form-item-control-wrapper">
                      <div class="ant-form-item-control" style="height: unset">
                        <div
                          style="display: inline-flex;flex-direction: row;flex-wrap: nowrap;align-content: center;justify-content: center;align-items: center;">
                          <a-radio-group button-style="solid" v-model:value="selectedSpecifications[specification.id]"
                                         @change="changeSelectedSpecification(specification)">
                            <a-radio-button v-for="(attributeValue,index) in  specification.attributeValueList"
                                            :disabled="attributeValue.id==null"
                                            :value="attributeValue.id">
                              <div
                                style="display: inline-flex;flex-direction: row;flex-wrap: nowrap;align-content: center;justify-content: center;align-items: center;">
                                {{ attributeValue.attributeValue }}
                                <a-button @click="toOpenAttributeValueModel(specification,index)"
                                          v-if="updateActionDate.state"
                                          :type="selectedSpecifications[specification.id]==null||selectedSpecifications[specification.id]!=attributeValue.id?'link':'primary'"
                                          icon="edit"
                                          style="height:16px;width:20px;margin-left: 5px;display: inline-flex;flex-direction: column;flex-wrap: nowrap;align-content: center;justify-content: center;align-items: center;"></a-button>
                              </div>
                            </a-radio-button>
                          </a-radio-group>
                          <a-button
                            @click="toOpenAttributeValueModel(specification,null)" v-if="updateActionDate.state"
                            icon="plus"
                            shape="circle"
                            style="margin-left: 10px;display: inline-flex;flex-direction: column;flex-wrap: nowrap;align-content: center;justify-content: center;align-items: center;"></a-button>
                        </div>
                      </div>
                    </div>
                  </div>
                </a-form>


              </a-col>
              <a-col :span="24" v-if="updateActionDate.state">
                <a-button @click="toOpenAttributeKeyModel(null)" icon="plus" type="primary">添加规格</a-button>
              </a-col>


              <a-modal v-model:visible="attributeKeyData.state">
                <a-form layout="inline" v-if="attributeKeyData.state">
                  <a-form-item label="规格名称">
                    <a-input v-model:value="attributeKeyData.data.attributeKey"></a-input>
                  </a-form-item>
                </a-form>
                <template #footer>
                  <a-button type="primary" @click="toSubmitAttributeKey">提交</a-button>
                  <a-button v-if="attributeKeyData.index!=null" type="danger" @click="toDeleteAttributeKey">
                    删除
                  </a-button>
                  <a-button @click="attributeKeyData.state=false">关闭</a-button>
                </template>
              </a-modal>
              <a-modal v-model:visible="attributeValueData.state">
                <a-form layout="inline" v-if="attributeValueData.state">
                  <a-form-item label="类别名称">
                    <a-input v-model:value="attributeValueData.data.attributeValue"></a-input>
                  </a-form-item>
                </a-form>
                <template #footer>
                  <a-button type="primary" @click="toSubmitAttributeValue">提交</a-button>
                  <a-button v-if="attributeValueData.index!=null" type="danger"
                            @click="toDeleteAttributeValue">删除
                  </a-button>
                  <a-button @click="attributeValueData.state=false">关闭</a-button>
                </template>
              </a-modal>

            </a-row>
          </a-card>
        </div>
        <div v-if="updateActionDate.data!=null" style="margin-top: 20px;">

          <a-card :loading="goodSpecificationDate.loading">
            <template #title>
              <div
                style="display: flex;flex-direction: row;flex-wrap: nowrap;align-content: center;justify-content: flex-start;align-items: center;">
                当前规格下的商品属性
                <a-tooltip placement="right">
                  <template slot="title">
                    上方每个规格的值都被选择后，此处可对对应的商品进行操作
                  </template>
                  <a-icon type="info-circle" style="margin: 0 5px;font-size: 16px;"/>
                </a-tooltip>
              </div>
            </template>


            <template #extra>
              <span v-if="goodSpecificationDate.createData.data!=null">
              <a-button type="primary"
                        v-if="!goodSpecificationDate.createData.state&&goodSpecificationDate.createData.data!=null&&goodSpecificationDate.createData.data.id!=null"
                        @click="goodSpecificationDate.createData.state=true">
                修改
              </a-button>
              <a-button type="primary" style="margin-left: 10px"
                        @click="toCreateGoodSpecification"
                        v-if="goodSpecificationDate.createData.state&&goodSpecificationDate.createData.data!=null&&goodSpecificationDate.createData.data.id!=null">
                保存
              </a-button>
              <a-button type="primary" style="margin-left: 10px"
                        v-if="goodSpecificationDate.createData.state&&goodSpecificationDate.createData.data!=null&&goodSpecificationDate.createData.data.id!=null"
                        @click="toCancelEditGoodSpecification">
                返回
              </a-button>
              <a-button style="margin-left: 10px" type="danger"
                        @click="toDeleteGoodSpecification"
                        v-if="!goodSpecificationDate.createData.state&&goodSpecificationDate.createData.data!=null&&goodSpecificationDate.createData.data.id!=null">
                删除该规格对应的属性
              </a-button>
              </span>
              <a-button style="margin-left: 10px" type="primary"
                        v-if="goodSpecificationDate.createData.state&&goodSpecificationDate.createData.data!=null&&goodSpecificationDate.createData.data.id==null"
                        @click="toCreateGoodSpecification">
                创建
              </a-button>
              <a-button style="margin-left: 10px" type="danger"
                        v-if="goodSpecificationDate.createData.state&&goodSpecificationDate.createData.data!=null&&goodSpecificationDate.createData.data.id==null"
                        @click="toCancelCreateGoodSpecification">
                取消创建
              </a-button>
            </template>
            <div v-if="attrAllSelected">
              <div v-if="goodSpecificationDate.createData.data!=null">
                <a-form layout="inline">
                  <a-row :gutter="48">
                    <a-col :lg="8" :md="12" :xs="24">
                      <a-form-item label="型号">
                        <a-input :read-only="!goodSpecificationDate.createData.state"
                                 v-model="goodSpecificationDate.createData.data.type"></a-input>
                      </a-form-item>
                    </a-col>
                    <a-col :lg="8" :md="12" :xs="24">
                      <a-form-item label="库存">
                        <a-input :read-only="!goodSpecificationDate.createData.state"
                                 v-model="goodSpecificationDate.createData.data.stock" type="number"></a-input>
                      </a-form-item>
                    </a-col>
                    <a-col :lg="8" :md="12" :xs="24">
                      <a-form-item label="单价(美元)">
                        <a-input :read-only="!goodSpecificationDate.createData.state"
                                 v-model="goodSpecificationDate.createData.data.price" type="number"></a-input>
                      </a-form-item>
                    </a-col>
                    <a-col :lg="8" :md="12" :xs="24">
                      <a-form-item label="单个订单能购买的最大数量">
                        <a-input :read-only="!goodSpecificationDate.createData.state"
                                 v-model="goodSpecificationDate.createData.data.maxNumber" type="number"></a-input>
                      </a-form-item>
                    </a-col>
                  </a-row>
                </a-form>
                <a-form>
                  <div data-v-53922493="" class="ant-row ant-form-item" style="height: auto;margin-bottom: 0">
                    <div class="ant-col ant-form-item-label"
                         style="margin-bottom: 10px;display: flex;flex-direction: row;flex-wrap: nowrap;align-content: center;justify-content: space-between;align-items: center;">
                      <label title="简介图" class="">价格优惠方案</label>
                      <span>
                        <a-button type="primary" @click="toPreAddPrice"
                                  v-if="goodSpecificationDate.createData.state">添加</a-button>
                      </span>
                    </div>
                    <div class="ant-col ant-form-item-control-wrapper">
                      <div class="ant-form-item-control" style="height: unset">
                        <a-table bordered size="small" :data-source="goodSpecificationDate.createData.data.numPriceList"
                                 :columns="columnsWithoutId">
                          <span slot="action" slot-scope="text, record" v-if="goodSpecificationDate.createData.state">
                            <a-button type="link" @click="toDeleteCreateDataPrice(record)">删除</a-button>
                          </span>
                        </a-table>
                        <a-modal v-model:visible="goodSpecificationDate.createData.modalState.state" @ok="toAddPrice">
                          <a-form layout="inline" v-if="goodSpecificationDate.createData.modalState.state">
                            <a-form-item label="数量">
                              <a-input type="number"
                                       v-model="goodSpecificationDate.createData.modalState.data.number"></a-input>
                            </a-form-item>
                            <a-form-item label="价格">
                              <a-input type="number"
                                       v-model="goodSpecificationDate.createData.modalState.data.realPrice"></a-input>
                            </a-form-item>
                          </a-form>
                        </a-modal>
                      </div>
                    </div>
                  </div>
                </a-form>
              </div>
              <div v-else>
                <a-result title="当前规格对应的商品属性尚未创建">
                  <template #extra>
                    <a-button key="console" type="primary" @click="toPreCreateGoodSpecification">
                      去创建！
                    </a-button>
                  </template>
                </a-result>
              </div>
            </div>
            <div v-else>
              <a-result title="请选择每个规格的指标">
              </a-result>
            </div>
          </a-card>
        </div>
      </a-spin>

    </div>
  </page-header-wrapper>
</template>

<script>
import router from '@/router'

import {
  addGoodSpecificationInfo, deleteGoodById, deleteGoodSpecificationInfoById,
  searchGoodById,
  searchGoodSpecificationInfoByAttr,
  updateGoodById, updateGoodStateById
} from "@/api/modules/GoodRequest";
import {searchTypeAsTree} from "@/api/modules/TypeRequest";
import {uploadPhoto} from "@/api/image";
import {notification} from "ant-design-vue";
import {addRecommendById} from "@/api/modules/MainPageRequest";

const columnsWithoutId = [
  {
    title: '数量',
    sorter(a, b) {
      return a.number - b.number
    },
    dataIndex: 'number',
    scopedSlots: {customRender: 'number'}
  },
  {
    title: '价格(美元)',
    dataIndex: 'realPrice',
    scopedSlots: {customRender: 'realPrice'}
  },
  {
    title: '操作',
    scopedSlots: {customRender: 'action'},
  }
]
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
  },
  ...columnsWithoutId
]
export default {
  name: "Goods",
  data() {
    return {
      value: null,
      columnsWithoutId,
      columns,
      loading: false,
      goodId: null,
      typeTreeList: null,
      typeDateLoading: false,
      typeMap: new Map(),
      goodData: null,
      goodSpecificationDate: {
        loading: false,
        data: null,
        createData: {
          state: false,
          data: null,
          isCreate: false,
          modalState: {
            state: false,
            data: null
          }
        }
      },
      requestList: [],
      selectedSpecifications: {},
      attributeKeyData: {
        state: false,
        data: null,
        index: null
      },
      attributeValueData: {
        state: false,
        data: null,
        specification: null,
        index: null
      },
      showPhotoData: {
        state: false,
        url: null
      },
      updateActionDate: {
        state: false,
        data: null
      },
      uploadingMainImage: false,
      uploadingSubImageImage: false,
    }
  },
  async mounted() {
    this.goodId = router.currentRoute.params.id;
    if (this.goodId == null) {
      router.push({
        path: '/goods'
      })
    } else {
      await this.toSearchType();
      await this.toRefreshGood();
    }
  },
  methods: {
    async toSearchType() {
      this.typeDateLoading = true;
      let _this = this;
      await searchTypeAsTree().then((res) => {
        if (res.status === 200) {
          _this.typeTreeList = res.data;

          let arr = [...res.data]

          for (let i = 0; i < arr.length; i++) {
            _this.typeMap.set(arr[i].id, arr[i]);
            if (arr[i].children == null) {
              delete arr[i].children
            }
            if (arr[i].children != null && arr[i].children.length > 0) {
              arr.push(...arr[i].children)
            }
          }

        } else {
          _this.$notification.warning({
            message: res.message
          })
        }
      }).catch((res) => {
        _this.$notification.warning({
          message: res.message
        })
      }).finally(() => {
        _this.typeDateLoading = false;
      })
    },
    async toDeleteGood() {
      let _this = this;
      this.$confirm({
        title: '确定删除？',
        onOk() {
          deleteGoodById(_this.goodId).then(() => {
            _this.$notification.success({
              message: '删除成功'
            })
            router.push({
              path: '/goods'
            })
          }).catch((res) => {
            _this.$notification.success(res)
          })
        }
      })
    },
    async toRefreshGood() {
      if (this.loading) return;
      this.loading = true;
      let _this = this;
      await searchGoodById(this.goodId).then((res) => {
        _this.goodData = res.data.goods[0]
        // _this.goodData.intro = _this.goodData.intro == null ? {} : JSON.parse(_this.goodData.intro)
        // _this.goodData.details = _this.goodData.details == null ? {} : JSON.parse(_this.goodData.details)
        _this.goodData.subImages = _this.goodData.subImages == null ? [] : JSON.parse(_this.goodData.subImages)
        _this.updateActionDate.data = JSON.parse(JSON.stringify(_this.goodData));
        _this.goodsSpecifications = res.data.goodsSpecifications
      }).catch(() => {
        router.push({
          path: '/goods'
        })
      }).finally(() => {
        _this.toCancelCreateGoodSpecification();
      })
      this.loading = false;
    },
    toStartEditGood() {
      this.selectedSpecifications = {};
      this.updateActionDate.state = true;
    },
    toCancelEditGood() {
      this.updateActionDate.data = JSON.parse(JSON.stringify(this.goodData));
      this.updateActionDate.state = false;
    },
    onGoodsTypeChange(value, selectedOptions) {
      console.log(value)
      if (value.length == 1) {
        this.updateActionDate.data.primaryTypeId = value[0]
        this.updateActionDate.data.secondaryTypeId = null;
        this.updateActionDate.data.tertiaryTypeId = null;
      } else if (value.length == 2) {
        this.updateActionDate.data.primaryTypeId = value[0]
        this.updateActionDate.data.secondaryTypeId = value[1]
        this.updateActionDate.data.tertiaryTypeId = null;
      } else if (value.length == 3) {
        this.updateActionDate.data.primaryTypeId = value[0]
        this.updateActionDate.data.secondaryTypeId = value[1]
        this.updateActionDate.data.tertiaryTypeId = value[2]
      }
      console.log(this.updateActionDate.data.primaryTypeId,
        this.updateActionDate.data.secondaryTypeId,
        this.updateActionDate.data.tertiaryTypeId)
    },
    onChangeIntro(value) {
      if (this.updateActionDate.state) {
        this.updateActionDate.data.intro = value;
      }
    },
    onChangeDetails(value) {
      if (this.updateActionDate.state) {
        this.updateActionDate.data.details = value;
      }
    },
    async toSubmitEditGood() {
      if (this.uploadingSubImageImage || this.uploadingMainImage) return;
      if (this.loading) return;
      let _this = this;
      _this.loading = true;
      let data = JSON.parse(JSON.stringify(this.updateActionDate.data))
      data.subImageList = data.subImages
      // data.intro = JSON.stringify(data.intro)
      // data.details = JSON.stringify(data.details)
      data.subImages = null
      data.price = null
      data.currentPrice = null
      data.updateAt = null
      data.createAt = null
      data.stock = null
      await updateGoodById(data)
      _this.loading = false;
      await _this.toRefreshGood();
      this.updateActionDate.state = false;
    },
    async toChangeStatus() {
      if (this.loading) return;
      let _this = this;
      _this.loading = true;
      await updateGoodStateById({
        id: this.goodId,
        status: this.updateActionDate.data.status == 1 ? 0 : 1
      }).then((res) => {
        _this.$notification.success({
          message: res.message
        })
      }).catch((res) => {
        _this.$notification.warning({
          message: res.message
        })
      });
      _this.loading = false;
      await _this.toRefreshGood();
    },
    toShowPhoto(file) {
      this.showPhotoData.url = file.url
      this.showPhotoData.state = true
    },
    handleMainImageChange({fileList}) {
      if (!this.updateActionDate.state) return;
      if (fileList.length == 0) {
        this.updateActionDate.data.mainImage = null
      } else {
        this.updateActionDate.data.mainImage = fileList[0].url
      }
    },
    handleSubImagesChange({fileList}) {
      if (!this.updateActionDate.state) return;
      let values = []
      fileList.filter((value) => {
        return value.url != null
      }).forEach((value) => {
        values.push(value.url)
      })
      this.updateActionDate.data.subImages = values;
    },
    handleUploadMainImage(e) {
      let _this = this;
      this.uploadingMainImage = true;
      let form = new FormData();
      form.set('photo', e.file);
      uploadPhoto(form).then((res) => {
        if (_this.updateActionDate.state) {
          _this.updateActionDate.data.mainImage = res.data
        }
      }).finally(() => {
        _this.uploadingMainImage = false;
      })
    },
    handleUploadSubImage(e) {
      let _this = this;
      this.uploadingSubImageImage = true;
      let form = new FormData();
      form.set('photo', e.file);
      uploadPhoto(form).then((res) => {
        if (_this.updateActionDate.state) {
          if (_this.updateActionDate.data.subImages == null) {
            _this.updateActionDate.data.subImages = [res.data]
          } else {
            _this.updateActionDate.data.subImages = [..._this.updateActionDate.data.subImages, res.data]
          }
        }
      }).finally(() => {
        _this.uploadingSubImageImage = false;
      })
      return false
    },
    changeSelectedSpecification(specification) {
      let _this = this;
      if (_this.updateActionDate.state) _this.selectedSpecifications = {};
    },
    toOpenAttributeKeyModel(index) {
      if (this.updateActionDate.data.specificationList == null) {
        this.updateActionDate.data.specificationList = []
      }
      if (index != null) {
        this.attributeKeyData.data = JSON.parse(JSON.stringify(this.updateActionDate.data.specificationList[index]))
        this.attributeKeyData.index = index;
      } else {
        this.attributeKeyData.data = {
          attributeKey: '',
          attributeValueList: [{attributeValue: '默认'}]
        }
        this.attributeKeyData.index = null;
      }
      this.attributeKeyData.state = true
      console.log(this.attributeKeyData)
    },
    toSubmitAttributeKey() {
      if (this.attributeKeyData.index == null) {
        this.updateActionDate.data.specificationList.push(this.attributeKeyData.data)
      } else {
        this.updateActionDate.data.specificationList[this.attributeKeyData.index].attributeKey = this.attributeKeyData.data.attributeKey
      }
      this.attributeKeyData.state = false
    },
    toDeleteAttributeKey() {
      this.updateActionDate.data.specificationList.splice(this.attributeKeyData.index, 1)
      if (this.updateActionDate.data.specificationList.length == 0) {
        this.updateActionDate.data.specificationList = [
          {
            attributeKey: '默认',
            attributeValueList: [{attributeValue: '默认'}]
          }
        ]
      }
      this.attributeKeyData.state = false
    },
    toOpenAttributeValueModel(specification, index) {
      this.attributeValueData.specification = specification;
      if (index != null) {
        this.attributeValueData.data = JSON.parse(JSON.stringify(specification.attributeValueList[index]))
        this.attributeValueData.index = index
      } else {
        this.attributeValueData.data = {
          attributeValue: ''
        }
        this.attributeValueData.index = null
      }
      this.attributeValueData.state = true
    },
    toSubmitAttributeValue() {
      if (this.attributeValueData.index == null) {
        this.attributeValueData.specification.attributeValueList.push(this.attributeValueData.data)
      } else {
        this.attributeValueData.specification.attributeValueList[this.attributeValueData.index].attributeValue = this.attributeValueData.data.attributeValue
      }
      this.attributeValueData.state = false
    },
    toDeleteAttributeValue() {
      this.attributeValueData.specification.attributeValueList.splice(this.attributeValueData.index, 1)
      if (this.attributeValueData.specification.attributeValueList.length == 0) {
        this.attributeValueData.specification.attributeValueList = [
          {attributeValue: '默认'}
        ]
      }
      this.attributeValueData.state = false
    },
    toCancelEditGoodSpecification() {
      this.goodSpecificationDate.createData.data = JSON.parse(JSON.stringify(this.goodSpecificationDate.data));
      this.goodSpecificationDate.createData.state = false;
    },
    toDeleteGoodSpecification() {
      let _this = this;
      this.$confirm({
        title: '确定删除？',
        onOk() {
          deleteGoodSpecificationInfoById(_this.goodSpecificationDate.createData.data.id).finally(() => {
            _this.toSearchGoodSpecificationInfoByAttr();
          })
        }
      })

    },
    toPreCreateGoodSpecification() {
      this.goodSpecificationDate.createData.isCreate = true;
      this.goodSpecificationDate.data = null;

      let a = [];
      for (let selectedSpecificationsKey in this.selectedSpecifications) {
        a.push({
          key: selectedSpecificationsKey,
          value: this.selectedSpecifications[selectedSpecificationsKey]
        })
      }

      this.goodSpecificationDate.createData.data = {
        goodsId: this.goodId,
        numPriceList: [],
        stock: 0,
        price: 0,
        specification: a
      };
      this.goodSpecificationDate.createData.state = true;
    },

    toPreAddPrice() {
      this.goodSpecificationDate.createData.modalState.data = {
        number: null,
        realPrice: null
      }
      this.goodSpecificationDate.createData.modalState.state = true;
    },

    toAddPrice() {
      let ok = true;
      let _this = this;
      for (let i = 0; i < this.goodSpecificationDate.createData.data.numPriceList.length; i++) {
        if (this.goodSpecificationDate.createData.data.numPriceList[i].number ===
          this.goodSpecificationDate.createData.modalState.data.number) {
          ok = false;
          break;
        }
      }
      if (ok) {
        this.goodSpecificationDate.createData.modalState.data.id = this.goodSpecificationDate.createData.modalState.data.number
        this.goodSpecificationDate.createData.data.numPriceList.push(this.goodSpecificationDate.createData.modalState.data)
        this.goodSpecificationDate.createData.modalState.state = false
      } else {
        notification.warning({
          message: '已存在该数量'
        })
      }
    },

    toDeleteCreateDataPrice(record) {
      let index = -1;
      for (let i = 0; i < this.goodSpecificationDate.createData.data.numPriceList.length; i++) {
        if (record.id == this.goodSpecificationDate.createData.data.numPriceList[i].id) {
          index = i;
          break;
        }
      }
      if (index != -1) {
        this.goodSpecificationDate.createData.data.numPriceList.splice(index, 1)
      }
    },

    toCreateGoodSpecification() {

      if (this.goodSpecificationDate.loading) return;
      let _this = this;

      let date = JSON.parse(JSON.stringify(this.goodSpecificationDate.createData.data))

      date.price = Number.parseFloat(date.price)
      date.stock = Number.parseInt(date.stock)
      date.maxNumber = Number.parseInt(date.maxNumber)

      delete date.createAt
      delete date.discountPrice
      delete date.updateAt
      if (!this.goodSpecificationDate.createData.isCreate) {
        delete date.goodsId
        date.specification = JSON.parse(date.specification)
      }

      for (let i = 0; i < date.numPriceList.length; i++) {
        if (this.goodSpecificationDate.createData.isCreate) {
          delete date.numPriceList[i].id
        } else {
          let find = false;

          for (let j = 0; j < this.goodSpecificationDate.data.numPriceList.length; j++) {
            if (this.goodSpecificationDate.data.numPriceList[j].id === date.numPriceList[i].id) {
              find = true;
              break;
            }
          }

          if (!find) {
            delete date.numPriceList[i].id
          }
        }

        delete date.numPriceList[i].createAt
        delete date.numPriceList[i].specificationId
        delete date.numPriceList[i].updateAt

        date.numPriceList[i].realPrice = Number.parseFloat(date.numPriceList[i].realPrice)
        date.numPriceList[i].number = Number.parseInt(date.numPriceList[i].number)
      }
      addGoodSpecificationInfo(date).then(() => {
        notification.success({message: '添加成功'})
        _this.toSearchGoodSpecificationInfoByAttr();
      }).catch((res) => {
        notification.warning(res)
      })
    },
    toCancelCreateGoodSpecification() {
      this.goodSpecificationDate.data = null;
      this.goodSpecificationDate.loading = false;
      this.goodSpecificationDate.createData.data = null;
      this.goodSpecificationDate.createData.state = false;
      this.goodSpecificationDate.createData.isCreate = true;
    },
    async toSearchGoodSpecificationInfoByAttr() {
      if (this.goodSpecificationDate.loading && this.requestList.length == 0) {
        this.requestList.push(this.toSearchGoodSpecificationInfoByAttr);
        return;
      }
      this.goodSpecificationDate.createData.isCreate = false;
      if (this.goodSpecificationDate.loading) return;
      this.goodSpecificationDate.loading = true
      let a = [];
      for (let selectedSpecificationsKey in this.selectedSpecifications) {
        a.push({
          key: selectedSpecificationsKey,
          value: this.selectedSpecifications[selectedSpecificationsKey]
        })
      }
      let _this = this;
      await searchGoodSpecificationInfoByAttr(a).then((res) => {
        if (res.data == null) {
          this.goodSpecificationDate.data = null;
          _this.goodSpecificationDate.createData.data = null;
          _this.goodSpecificationDate.createData.state = false;
        } else {
          _this.goodSpecificationDate.data = res.data.GoodsSpecification;
          _this.goodSpecificationDate.data.numPriceList = res.data.numPriceList;

          _this.goodSpecificationDate.createData.data = JSON.parse(JSON.stringify(_this.goodSpecificationDate.data));
          _this.goodSpecificationDate.createData.state = false;
        }
      }).catch().finally(() => {
        _this.goodSpecificationDate.loading = false
      })

      this.requestList.forEach(async (f) => {
        await f()
      })
      this.requestList = []
    },

    backToList() {
      console.log(11)
      this.$router.back();
    },
    async toAddToMainPageRecommendGoods() {
      await addRecommendById(this.goodId).then(res => {
        this.$notification.success({
          message: '添加成功'
        })
      })
    },
  },
  computed: {
    mainImage() {
      if (this.updateActionDate.data != null && this.updateActionDate.data.mainImage != null) {
        return [{
          name: this.updateActionDate.data.mainImage,
          uid: -1,
          status: 'done',
          url: this.updateActionDate.data.mainImage
        }]
      } else {
        return []
      }
    },
    subImages() {
      if (this.updateActionDate.data != null && this.updateActionDate.data.subImages != null) {
        let values = [];
        this.updateActionDate.data.subImages.forEach((value, index) => {
          values.push({
            name: value,
            uid: index,
            status: 'done',
            url: value
          })
        })
        return values
      } else {
        return []
      }
    },
    attrAllSelected() {
      if (this.updateActionDate.data == null || this.updateActionDate.data.specificationList == null || this.updateActionDate.data.specificationList.length == 0) return false;
      if (this.selectedSpecifications == null) return false;
      return Object.keys(this.selectedSpecifications).length === this.updateActionDate.data.specificationList.length
    },
  },
  watch: {
    selectedSpecifications: {
      async handler() {
        if (this.attrAllSelected) {
          await this.toSearchGoodSpecificationInfoByAttr();
        } else {
          if (this.goodSpecificationDate.data != null) this.goodSpecificationDate.data = null;
          if (this.goodSpecificationDate.createData.data != null) this.goodSpecificationDate.createData.data = null;
          if (this.goodSpecificationDate.createData.state !== false) this.goodSpecificationDate.createData.state = false;
        }
      },
      deep: true
    }
  }
}
</script>

<style scoped>

</style>